package club.banyuan;

public class Rpn {
  private static Integer calc(Integer left, Integer right, String s) {
    Integer r = null;
    switch (s.charAt(0)) {
      case '+':
        r = left + right;
        break;
      case '-':
        r = left - right;
        break;
      case '*':
        r = left * right;
        break;
      case '/':
        r = left / right;
        break;
    }
    return r;
  }

  static Integer rpn(String[] in) {
    MyStack<Integer> stack = new MyStack<>();

    // 遍历in中间的每个字符串进行处理
    for (String s : in) {
      try {
        Integer i = Integer.valueOf(s);
        // 不抛出异常说明s是数字
        // 如果是数字，则入栈
        stack.push(i);
      } catch (NumberFormatException e) {
        // 说明s是符号
        // 取两个操作数出来进行运算， 结果再入栈
        Integer right = stack.pop();
        Integer left = stack.pop();
        var r = calc(left, right, s);
        stack.push(r);
      }
    }
    // 最后栈里应该还剩下一个元素
    return stack.pop();
  }

  public static void main(String[] args) {
    //    String[] in = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
    String[] in2 = {"4", "13", "5", "/", "+"};
    System.out.println(rpn(in2));
  }
}
